type NavigationTiming = {
    dns: number
    tcp: number
    ttfb: number
    domReady?: number
    pageLoad: number
    redirect?: number
    domInteractive?: number
}

/**
 * 导航计时监控（TTFB, DNS, TCP 等）
 */
export function trackNavigationTiming(report: (data: NavigationTiming) => void) {
    // performance.getEntriesByType 要获取的性能条目的类型，例如 "navigation"、"resource"、"mark" 等
    if (typeof window === "undefined" || !("performance" in window) || !performance.getEntriesByType) return

    // 页面完全加载后上报导航数据
    window.addEventListener("load", () => {
        const [navigationEntry] = performance.getEntriesByType("navigation") as PerformanceNavigationTiming[]
        if (!navigationEntry) return

        const metrics: NavigationTiming = {
            // domainLookupStart: 域名查询开始的时间戳
            // domainLookupEnd: 域名查询结束的时间戳
            dns: navigationEntry.domainLookupEnd - navigationEntry.domainLookupStart,
            // connectStart: 请求向服务器发送连接请求时的时间戳
            // connectEnd: 浏览器和服务器之前建立连接的时间戳
            tcp: navigationEntry.connectEnd - navigationEntry.connectStart, //
            // responseStart:浏览器从服务器接收到第一个字节时的时间戳
            // responseStart: 浏览器从服务器接收到第一个字节时的时间戳
            ttfb: navigationEntry.responseStart - navigationEntry.requestStart, //从客户端发出请求到服务器返回第一个字节的时间
            // loadEventEnd: load 时间结束时的时间
            pageLoad: navigationEntry.loadEventEnd - navigationEntry.startTime,
            redirect: navigationEntry.redirectEnd - navigationEntry.redirectStart,
            domInteractive: navigationEntry.domInteractive - navigationEntry.startTime
        }
        // // domContentLoadedEventStart: DOMContentLoaded 事件结束时的时间戳
        // // domContentLoadedEventEnd: DOMContentLoaded 事件触发时的时间戳，所有需要执行的脚本执行完毕
        // domReady: navigationEntry.domComplete - navigationEntry.domLoading,

        // 旧版domReady的替代方案
        if ("domComplete" in navigationEntry) {
            metrics.domReady = (navigationEntry as any).domComplete - (navigationEntry as any).domLoading
        }

        report(metrics)
    })
}
